package com.springcloud.jwt;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 每次用户名密码验证后刷新token,适用于token过期时间较短的场景<br>
 * 缺点:每次请求都要刷新，增加服务器功耗,前端所存储的token也要每次重新赋值
 *
 * @author Administrator
 *
 */
@Component
public class JwtSuccessTokenFilter extends OncePerRequestFilter {
    private Logger logger = LoggerFactory.getLogger(getClass());

    @Autowired
    private JwtConfigProperty jwtConfig;
    @Autowired
    private JwtUtil jwtUtil;

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain)
            throws ServletException, IOException {
        String tokenHead = this.jwtConfig.getTokenHead();
        try {
            String username = SecurityContextHolder.getContext().getAuthentication().getName();
            String token = jwtUtil.generateToken(username);
            response.setHeader(this.jwtConfig.getHeader(), tokenHead + token);
        }catch (Exception e) {
//            response.getWriter().write("验证失败");
        }
        filterChain.doFilter(request, response);
    }

}
